#include "chatclient.hpp"
#include "json.hpp"
#include "public.hpp"
#include "clientservice.hpp"

#include <boost/bind.hpp>
#include <iostream>


using std::cout;
using std::endl;
//含参构造函数
ChatClient::ChatClient(EventLoop* loop,
            const InetAddress& serverAddr,
            const string& name)
    :_client(loop,serverAddr,name),_loop(loop){
    
    //绑定连接事件
    this->_client.setConnectionCallback(boost::bind(&ChatClient::onConnection,this,boost::placeholders::_1));

    //绑定消息响应事件
    this->_client.setMessageCallback(
            boost::bind(&ChatClient::onMessage,this,
                boost::placeholders::_1,boost::placeholders::_2,boost::placeholders::_3));

    //_client.enableRetry();
}

void ChatClient::connect(){
    _client.connect();
}

//终止服务器
void ChatClient::stop(){
    _client.stop();
}

//断开连接
void ChatClient::disconnect(){
    _client.disconnect();
}

void ChatClient::onConnection(const TcpConnectionPtr& conn){
    _conn_mutex.lock();
    if(conn->connected()){
        ClientService::getInstacnce()->setTcpConnectionPtr(conn);
    }
    _conn_mutex.unlock();
    
    //日志
    LOG_INFO<<conn->localAddress().toIpPort()<<" -> "
            <<conn->peerAddress().toIpPort()<<" is "
            <<(conn->connected() ? "UP" : "DOWN")
            <<". ";

}


void ChatClient::onMessage(const TcpConnectionPtr& conn,    //连接
                    Buffer* buffer,                 //缓冲区
                    Timestamp time){                //接收到数据时候的时间
    
    using nlohmann::json;
    
    //将缓冲区内容转为字符串保存
    string buf=buffer->retrieveAllAsString();
    
    //翻译成json对象
    json js=json::parse(buf);

    //解析json
    ClientService::getInstacnce()->IOparseMsgType(js);


}

